/**
 * Created by zhoulin on 2019/4/3.
 */
var E = window.wangEditor;

var editor = new E('#editor');
var app = new Vue({
    el: '#app',
    data: {
        permissions: ['vote:add', 'vote:update'],//本页权限数组
        info: {},
        desc: '',
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        that.getTagList();
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);
            return;
        }
        if (!empty(aGET.id)) {
            that.getInfoById(aGET.id);
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        getTagList: function () {
            var that = this;
            Get(that, _HOST + _API.common_tag_getTagsByType + "?type=7")
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        initSelect(response.list);
                    }
                });
        },
        getInfoById: function (id) {
            var that = this;
            Get(that, _HOST + _API.organization_vote_getById + "?id=" + id)
                .then(function (response) {
                    // 响应成功回调
                    if (response.success) {
                        var list = response.data;
                        var oldImgId = "";
                        var oldAudioId = "";
                        for (var item in list) {
                            if (item == 'imgId') {
                                oldImgId = list[item];
                                continue;
                            }
                            if (item == 'audioId') {
                                oldAudioId = list[item];
                                continue;
                            }
                            if (item == 'details') {
                                editor.txt.html(list[item]);
                                continue;
                            }
                            if (item == 'showUrl') {
                                initFileUpload(list[item]);
                                continue;
                            }
                            if (item == 'audioUrl') {
                                initAudioFileUpload(list[item]);
                                continue;
                            }
                            if (item == 'imgs') {
                                initFilesUpload(list[item]);
                                continue;
                            }
                            if (item == 'isTop') {
                                $("#Form select[name='isTop']").val(list[item]);
                                continue;
                            }
                            if (item == 'isPush') {
                                $("#Form select[name='isPush']").val(list[item]);
                                continue;
                            }
                            if (item == 'limitation') {
                                $("#Form select[name='limitation']").val(list[item]);
                                continue;
                            }
                            if (item == 'digest') {
                                that.desc = list[item];
                                continue;
                            }
                            if (item == 'tagIds') {
                                selectTags(list[item]);
                                continue;
                            }
                            if (item == 'beginTime') {
                                $("#Form input[name='" + item + "']").val(formatDateTime(list[item]));
                                continue;
                            }
                            if (item == 'expiredTime') {
                                $("#Form input[name='" + item + "']").val(formatDateTime(list[item]));
                                continue;
                            }
                            $("#Form input[name='" + item + "']").val(list[item]);
                        }
                        $("#Form input[name='oldImgId']").val(oldImgId);
                        $("#Form input[name='oldAudioId']").val(oldAudioId);
                        $("#Form").data('bootstrapValidator').destroy();
                        $('#Form').data('bootstrapValidator', null);
                        Validator();
                    } else {
                        layer.msg(response.msg, {time: 1500, icon: 5});
                    }
                })
        },
        // 添加
        add: function () {
            var that = this;
            var param = formToJson($("#Form").serialize());
            param.details = editor.txt.html();
            param.imgIds = $('#uploadImgs').getImgIdArr();
            // 得到标签
            var tagArr = $("#tags").val();
            var ids = "";
            if (!empty(tagArr)) {
                for (let i = 0; i < tagArr.length; i++) {
                    ids += tagArr[i];
                    if ((i + 1) != tagArr.length) {
                        ids += ",";
                    }
                }
            }
            param['tagIds'] = ids;
            console.log(param);
            Post(that, _HOST + _API.organization_vote_add, param, true, '')
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        // 修改
        update: function () {
            var that = this;
            var param = formToJson($("#Form").serialize());
            param.details = editor.txt.html();
            param.imgIds = $('#uploadImgs').getImgIdArr();
            // 得到标签
            var tagArr = $("#tags").val();
            var ids = "";
            if (!empty(tagArr)) {
                for (let i = 0; i < tagArr.length; i++) {
                    ids += tagArr[i];
                    if ((i + 1) != tagArr.length) {
                        ids += ",";
                    }
                }
            }
            param['tagIds'] = ids;
            console.log(param);
            Post(that, _HOST + _API.organization_vote_update, param, true, '')
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            layer.msg(response.msg, {time: 1500, icon: 1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
    },
});

// 初始化多选
function initSelect(datas) {
    var select = $("#tags");
    for (var i = 0; i < datas.length; i++) {
        select.append("<option value='" + datas[i].id + "'>"
            + datas[i].name + "</option>");
    }
    select.selectpicker('val', '');
    select.selectpicker('refresh');
}

// 选中tag
function selectTags(value) {
    var s = document.getElementById("tags");
    console.log(value);
    if (!empty(value)) {
        var tagsArr = value.split(",");
        $('.selectpicker').selectpicker('val', tagsArr);
    }
}

$('#Form').data('bootstrapValidator', null);
Validator();

function initFileUpload(url) {
    $("#fileUploadBtn").fileinput('destroy');
    $("#fileUploadBtn").fileinput({
        language: "zh",
        uploadUrl: _HOST + _API.common_file_ossUpload,
        ajaxSettings: {
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': ''
            }
        },
        browseClass: "btn btn-success",
        browseLabel: "上传图片",
        browseIcon: "<i class=\"glyphicon glyphicon-picture\"></i> ",
        allowedFileExtensions: ['jpg', 'gif', 'png'],
        showUpload: false,
        dropZoneEnabled: true,
        showPreview: true,
        minFileCount: 1,
        maxFileCount: 1,
        initialPreviewAsData: true,
        initialPreview: [
            url
        ],
        initialPreviewConfig: [
            {
                caption: url,
                size: 329892,
                width: "120px",
                url: url,
                key: 1
            },
        ]
    }).on("filebatchselected", function (event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function (event, data, previewId, index) {
        if (data.response.status) {
            $("#file .file-caption-name").text(data.response.attachemId);
            $("#articleImg").val(data.response.attachemId);
        } else {
            parent.layer.msg(data.response.msg, {time: 1500, icon: 5});
        }
    });
    $(".kv-file-remove").remove();
}

function initAudioFileUpload(url) {
    $("#fileUploadAudioBtn").fileinput('destroy');
    $("#fileUploadAudioBtn").fileinput({
        language: "zh",
        uploadUrl: _HOST + _API.common_file_ossUpload,
        ajaxSettings: {
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': ''
            }
        },
        browseClass: "btn btn-success",
        browseLabel: "上传音频",
        browseIcon: "<i class=\"glyphicon glyphicon-headphones\"></i> ",
        allowedFileExtensions: ['mp3', 'aif', 'wav', 'midi','mka'],
        showUpload: false,
        dropZoneEnabled: true,
        showPreview: true,
        minFileCount: 1,
        maxFileCount: 1,
        initialPreviewAsData: true,
        initialPreview: [
            url
        ],
        initialPreviewConfig: [
            {
                caption: url,
                size: 329892,
                type:'audio',
                filetype:'audio/mp3',
                width: "120px",
                url: url,
                key: 1
            },
        ]
    }).on("filebatchselected", function (event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function (event, data, previewId, index) {
        if (data.response.status) {
            $("#file .file-caption-name").text(data.response.attachemId);
            $("#audioId").val(data.response.attachemId);
        } else {
            parent.layer.msg(data.response.msg, {time: 1500, icon: 5});
        }
    });
    $(".kv-file-remove").remove();
}

function initFilesUpload(imgs) {
    var uploadImgs = $('#uploadImgs').diyUpload({
        url: _HOST + _API.common_file_ossUpload,
        begin: function() {
            layer.load(0, {shade: false});
        },
        success: function (data) {
            layer.closeAll();
            console.log("上传成功！");
        },
        error: function (err) {
            layer.closeAll();
            layer.msg(err, {time: 1500, icon: 5});
            console.log("上传失败！");
        },
        headers: {
            'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
        },
        previewArr: imgs,
        thumb: {
            width: 120,
            height: 90,
            quality: 100,
            allowMagnify: true,
            crop: true,
            // type: "image/jpeg"
        }
    });
}

$(function () {
    editor.customConfig.uploadImgServer = _HOST + _API.common_file_ossWe;
    editor.customConfig.uploadFileName = 'file';
    editor.customConfig.uploadImgHeaders = {
        'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
        'permCoding': '',
        'enctype': 'multipart/form-data'
    };
    editor.customConfig.zIndex = 100;
    editor.create();
    if (empty(aGET.id)) {
        initFileUpload('');
        initAudioFileUpload('');
        initFilesUpload('');
    }
});

function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '名称不能为空'
                    },
                    stringLength: {
                        max: 100,
                        message: '名称长度最多100个字符'
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        if (empty(aGET.id)) {
            app.add();
        } else {
            app.update();
        }
    });
}
